package hevs.activities;

import hevs.greencontrol.R;
import hevs.greencontrol.R.id;
import hevs.greencontrol.R.layout;
import hevs.utils.ConnectionManager;
import hevs.utils.Error;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
 * This class allow the user to login the application.
 * @author Jonathan Moreira, Jun Yang, Natal Venetz, Ivan Samardziev
 *
 */
public class Login extends Activity implements OnClickListener{

	// DATA
	private final static String LOGIN="login.txt";
	private EditText username;
	private EditText password;
	private CheckBox automaticLogin;
	private Button loginButton;
	//private UserData userData;

	/**
	 * Method called on creation of activity
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		// instanciate the edit boxes
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		
		// instanciate the checkbox
		automaticLogin = (CheckBox) findViewById(R.id.automaticLogin);

		// instanciate the button
		loginButton = (Button) findViewById(R.id.login_button);
	}

	/**
	 * Method called on start of activity
	 */
	@Override
	protected void onStart()
	{
		super.onStart();

		// give the button a listener control
		loginButton.setOnClickListener(this);
	}

	/**
	 * Switch the actions when executed on click
	 */
	@Override
	public void onClick(View view)
	{
		if(view.getId() == R.id.login_button)
		{
			//login();
			startActivity(new Intent(this,Selector.class));
		}
	}

	/**
	 * Method used to check the user name and password and make login
	 */
	private void login() {
		// clear the list of map before getting a new one
	//	UserData.trashEverything();
	//	userData = UserData.getInstance();

		ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("username",username.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair("userpw",password.getText().toString()));

	
		try
		{	
			JSONArray jArrayUser = ConnectionManager.sendhttpPost("login.php", nameValuePairs);
			if(jArrayUser != null)
			{			
				int idUser =  jArrayUser.getJSONObject(0).getInt("idUser");

				if(idUser > 0)
				{ 
				//	userData.setIdUser(idUser);
					
					// If the login automatic checkbox is true
					if(automaticLogin.isChecked()==true)
					{
						// We save the login infos
						saveLoginInfos();
					}

					//userData.setSmartObjectToEdit(new SmartObject(0,"",0));
					
					startActivity(new Intent(this,Selector.class));
					
					this.finish();
				}
				else
				{
					Error.toastNotif(this, "Error wrong password/username", 2);
				}
			}
			else
			{
				Error.serviceFunctionError(this);
			}
		}
		catch(JSONException e)
		{
			Log.e("log_tag", "Error parsing data "+e.toString());
		}
	}
	
	@Override
	public void onResume()
	{
		super.onResume();

		try
		{
			InputStream inputStream = openFileInput(LOGIN);

			if (inputStream != null)
			{
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
				BufferedReader reader = new BufferedReader(inputStreamReader);

				// read automatic login
				String al = reader.readLine();

				// read username
				String un = reader.readLine();

				// read password
				String pw = reader.readLine();
				
				inputStream.close();
				
				// set username and password
				username.setText(un);
				password.setText(pw);

				// if automatic login == true, launch login method
				if(al.equals("true"))
				{					
					login();
				}
			}
		}
		catch (java.io.FileNotFoundException e)
		{
			// file login.txt not created
		}
		catch (Throwable t)
		{
			Toast.makeText(this, "Exception : " + t.toString(), 2000).show();
		}
	}

	/**
	 * Method to save the login infos in a txt fill
	 * - Called only if the user has checked the automatic login checkbox
	 */
	public void saveLoginInfos()
	{
		try
		{
			OutputStreamWriter output = new OutputStreamWriter(openFileOutput(LOGIN, 0));

			output.write("true" + "\n");
			output.write(username.getText().toString() + "\n");
			output.write(password.getText().toString());
			output.close();
		}
		catch (Throwable t)
		{
			Toast.makeText(this, "Exception : " + t.toString(), 2000).show();
		}
	}
}
